<template>
  <div class="home-container">
    <notice v-if="noticeMsg.length > 0" :msg="noticeMsg" :delay="20000" />
    <!-- 今日数据 -->
    <div class="todays">
      <div class="panel">
        <span class="icon"><svg-icon icon-class="visitors" /></span>
        <router-link :to="{name:'Statistics'}">
          <div>
            <p class="title">今日访客</p>
            <p class="today">{{ visitor.today }}</p>
            <p class="history">总访客量：{{ visitor.history }}</p>
          </div>
        </router-link>
      </div>
      <div class="panel">
        <span class="icon"><svg-icon icon-class="order-list" /></span>
        <router-link :to="{name:'Statistics'}">
          <div>
            <p class="title">今日订单量</p>
            <p class="today">{{ order.today }}</p>
            <p class="history">总订单量：{{ order.history }}</p>
          </div>
        </router-link>
      </div>
      <div class="panel">
        <span class="icon"><svg-icon icon-class="sales-money" /></span>
        <router-link :to="{name:'Statistics'}">
          <div>
            <p class="title">今日销量</p>
            <p class="today">{{ sale.today }}</p>
            <p class="history">总销量：{{ sale.history }}</p>
          </div>
        </router-link>
      </div>
      <div class="panel">
        <span class="icon"><svg-icon icon-class="goods-number" /></span>
        <router-link :to="{name:'Statistics'}">
          <div>
            <p class="title">上架商品数</p>
            <p class="today">{{ goods.on }}</p>
            <p class="history">商品总量：{{ goods.total }}</p>
          </div>
        </router-link>
      </div>
    </div>

    <div class="bottom">
      <!-- 订单提醒、折线统计图 -->
      <div class="left">
        <div class="order-tips">
          <h2>订单提醒</h2>
          <ul class="tips-list">
            <li><span class="text">待付款订单</span><span class="num" @click="toNeedPage('/order/list','01500001')">{{ orderStatistics.pendingPayment }}</span></li>
            <li><span class="text">待收货订单</span><span class="num" @click="toNeedPage('/order/list','01500003')">{{ orderStatistics.pendingOrders }}</span></li>
            <li><span class="text">待发货订单</span><span class="num" @click="toNeedPage('/order/list','01500002')">{{ orderStatistics.pendingShip }}</span></li>
            <li><span class="text">待退款售后订单</span><span class="num" @click="toNeedPage('/order/after_sale','02000001')">{{ orderStatistics.pendingRefund }}</span></li>
            <li><span class="text">待回复评价</span><span class="num" @click="toNeedPage('/comments/list','0')">{{ orderStatistics.completed }}</span></li>
          </ul>
        </div>
        <div class="chart-title">
          <div class="title">
            <h2>销售统计</h2>
            <div class="date-picker">
              <el-dropdown @command="changeDate1">
                <span class="el-dropdown-link">
                  {{ statisticsStr }}<i class="el-icon-arrow-down el-icon--right" />
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item :command="7">近7天</el-dropdown-item>
                  <el-dropdown-item :command="30">近30天</el-dropdown-item>
                  <el-dropdown-item :command="180">近半年</el-dropdown-item>
                  <el-dropdown-item :command="365">近1年</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </div>
          </div>
          <div class="summary">
            <span>{{ chartDate }}天销售额</span>
            <span class="value">{{ salesTotal | fixedPrice }}</span>
            <span>共计<span class="num">{{ orderTotal }}</span>笔订单</span>
          </div>
        </div>
        <div v-loading="chartLoading" class="chart-container">
          <chart id="salesChart" :options="chartOptions" height="100%" width="100%" @dataZoom="getZoomData" />
        </div>
      </div>
      <div class="right">
        <div class="title">
          <el-link :underline="false" @click="toGoodsRanking()"><h2>商品销售量排行</h2></el-link>
          <el-dropdown @command="changeDate">
            <span class="el-dropdown-link">
              {{ salesSortStr }}<i class="el-icon-arrow-down el-icon--right" />
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item :command="0">全部</el-dropdown-item>
              <el-dropdown-item :command="7">近7天</el-dropdown-item>
              <el-dropdown-item :command="30">近30天</el-dropdown-item>
              <el-dropdown-item :command="365">近1年</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
        <p class="sum">总销售量 <span class="num">{{ pdtSort.allSalesNum }}</span> 件</p>
        <div v-loading="sortLoading" class="pdt-box">
          <div class="pdt-list">
            <div v-for="(pdt, index) in pdtSort.sales" :key="index" class="pdt">
              <div class="box" @click="toDetail(pdt.mdseId)">
                <p class="index">{{ index+1 }}</p>
                <p class="img"><img :src="qnPath(pdt.image.split(',')[0])" :alt="pdt.name"></p>
                <div class="info">
                  <p class="name">{{ pdt.name }}</p>
                  <p class="property">{{ pdt.propertyValueName }}</p>
                </div>
              </div>
              <div class="count">{{ pdt.salesNum }}件</div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex';
import Notice from './components/Notice';
import Chart from '@/components/Charts/LineMarker';
import { getNotice, getShopData, getShopOrder, getSalesData, getMdseSalesData } from '@/api/statistics';
import { lastDates } from 'recentlyjs';
export default {
  name: 'Home',
  components: {
    Notice,
    Chart
  },
  data() {
    return {
      sortLoading: false,
      chartLoading: false,
      noticeMsg: [],
      visitor: {
        today: 0,
        history: 0
      },
      order: {
        today: 0,
        history: 0
      },
      sale: {
        today: 0,
        history: 0
      },
      goods: {
        on: 0,
        total: 0
      },
      // 订单提醒
      orderStatistics: {},
      // 图表配置项
      statisticsSales: [],
      statisticsOrders: [],
      chartOptions: {
        backgroundColor: '#fff',
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            lineStyle: {
              color: '#57617B'
            }
          }
        },
        dataZoom: [{
          type: 'inside'
        }],
        legend: {
          top: 20,
          icon: 'rect',
          itemWidth: 14,
          itemHeight: 5,
          itemGap: 13,
          data: ['订单量', '销售额'],
          left: 'center',
          textStyle: {
            fontSize: 12,
            color: '#3C4353'
          }
        },
        grid: {
          top: 100,
          left: '2%',
          right: '2%',
          bottom: '2%',
          containLabel: true
        },
        xAxis: [{
          type: 'category',
          boundaryGap: false,
          axisLine: {
            lineStyle: {
              color: '#57617B'
            }
          },
          data: lastDates(30)
        }],
        yAxis: [{
          type: 'value',
          name: '销售额',
          axisTick: {
            show: false
          },
          axisLine: { // 坐标轴线
            lineStyle: {
              color: '#57617B'
            }
          },
          axisLabel: {
            formatter: '{value} 万',
            margin: 10,
            textStyle: {
              fontSize: 14
            }
          },
          splitLine: { // 分隔线
            lineStyle: {
              color: '#dce1ee',
              type: 'dashed'
            }
          }
        },
        {
          type: 'value',
          name: '订单量',
          position: 'right',
          axisTick: {
            show: false
          },
          axisLine: {
            lineStyle: {
              color: '#57617B'
            }
          },
          axisLabel: {
            formatter: '{value} 单',
            margin: 10,
            textStyle: {
              fontSize: 14
            }
          },
          splitLine: {
            lineStyle: {
              color: '#dce1ee',
              type: 'dashed'
            }
          }
        }],
        series: [
          {
            name: '销售额',
            type: 'line',
            smooth: true,
            symbol: 'circle',
            symbolSize: 5,
            showSymbol: false,
            lineStyle: {
              normal: {
                width: 1
              }
            },
            areaStyle: {
              normal: {
                color: new this.$echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                  offset: 0,
                  color: 'rgba(0, 136, 212, 0.3)'
                }, {
                  offset: 0.8,
                  color: 'rgba(0, 136, 212, 0)'
                }], false),
                shadowColor: 'rgba(0, 0, 0, 0.1)',
                shadowBlur: 10
              }
            },
            itemStyle: {
              normal: {
                color: 'rgb(0,136,212)',
                borderColor: 'rgba(0,136,212,0.2)',
                borderWidth: 12
              }
            },
            data: []
          },
          {
            name: '订单量',
            type: 'line',
            smooth: true,
            symbol: 'circle',
            symbolSize: 5,
            showSymbol: false,
            yAxisIndex: 1, // 坐标轴位置
            lineStyle: {// 折线样式
              normal: {
                width: 1,
                color: '#FFA4A6'
              }
            },
            areaStyle: { // 区域填充样式
              normal: {
                color: new this.$echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                  offset: 0,
                  color: 'rgba(255,164,166, 0.5)'
                }, {
                  offset: 0.8,
                  color: 'rgba(255,164,166, 0)'
                }], false),
                shadowColor: 'rgba(0, 0, 0, 0.1)',
                shadowBlur: 10
              }
            },
            itemStyle: { // 指示点、示例样式
              normal: {
                color: 'rgb(255,164,166)',
                borderColor: 'rgba(255,164,166,0.27)',
                borderWidth: 12

              }
            },
            data: []
          }
        ]
      },

      salesTotal: 0,
      orderTotal: 0,
      chartDate: 30, // 图表展示数据的区间
      salesSortStr: '全部',
      statisticsStr: '近一个月',
      pdtSort: {
        allSalesNum: 0,
        sales: []
      }
    };
  },
  computed: {
    ...mapGetters([
      'shopInfo'
    ])
  },
  created() {
    this.getNotice();
    this.getShopData();
    this.getShopOrder();
    this.getMdseSalesData('0');
    this.getSalesData('30');
  },
  methods: {
    toDetail(id) {
      sessionStorage.setItem('goodsDetail', id);
      this.$router.push('/goods/detail');
    },
    toGoodsRanking() {
      this.$router.push('/goods/ranking');
    },
    getNotice() { // 公告
      new Promise((resolve, reject) => {
        getNotice({ pageSize: 10, pageNo: 1 }).then(({ data }) => {
          const arr = [];
          data.notice.map(notice => {
            arr.push(notice.name);
          });
          this.noticeMsg = arr;
          resolve(data);
        }).catch(error => {
          reject(error);
        });
      });
    },
    getShopData() { // 访客 订单量 销量 上架数量
      const shopId = this.shopInfo.id;
      new Promise((resolve, reject) => {
        getShopData({ shopId }).then(({ data }) => {
          this.visitor.today = data.browseNum;
          this.visitor.history = data.allBrowseNum;
          this.order.today = data.orderNum;
          this.order.history = data.allOrderNum;
          this.sale.today = data.salesNum;
          this.sale.history = data.allSalesNum;
          this.goods.on = data.upperShelfNum;
          this.goods.total = data.allMdseNum;
          resolve(data);
        }).catch(error => {
          reject(error);
        });
      });
    },
    getShopOrder() { // 订单数据
      const shopId = this.shopInfo.id;
      new Promise((resolve, reject) => {
        getShopOrder({ shopId }).then(({ data }) => {
          const { pendingPayment, pendingOrders, pendingRefund, completed, pendingShip } = data;
          this.orderStatistics = { pendingPayment, pendingOrders, pendingRefund, completed, pendingShip };
          resolve(data);
        }).catch(error => {
          reject(error);
        });
      });
    },
    getSalesData(day) { // 统计
      const shopId = this.shopInfo.id;
      this.chartLoading = true;
      new Promise((resolve, reject) => {
        getSalesData({ shopId, day: day + '' }).then(({ data }) => {
          const { sales, order } = data;
          const newSales = sales.map(price => price / 10000 / 100);
          this.chartOptions.xAxis[0].data = lastDates(day);
          this.chartOptions.series[0].data = newSales;
          this.chartOptions.series[1].data = order;
          this.initData(this.chartOptions);
          this.chartLoading = false;
          resolve(data);
        }).catch(error => {
          reject(error);
        });
      });
    },
    getMdseSalesData(day) { // 销售排行
      const shopId = this.shopInfo.id;
      this.sortLoading = true;
      new Promise((resolve, reject) => {
        getMdseSalesData({ shopId, day, pageNo: 1, pageSize: 10 }).then(({ data }) => {
          this.pdtSort = data;
          this.sortLoading = false;
          resolve(data);
        }).catch(error => {
          reject(error);
        });
      });
    },
    changeDate(item) {
      let str = '';
      switch (item) {
        case 7:
          str = '近7天';
          break;
        case 30:
          str = '近30天';
          break;
        case 365:
          str = '近1年';
          break;
        default:
          str = '全部';
      }
      this.salesSortStr = str;
      this.getMdseSalesData(item + '');
    },
    changeDate1(item) {
      let str = '';
      switch (item) {
        case 7:
          str = '近7天';
          break;
        case 30:
          str = '近30天';
          break;
        case 180:
          str = '近半年';
          break;
        case 365:
          str = '近1年';
      }
      this.statisticsStr = str;
      this.chartDate = item;
      this.getSalesData(item);
    },
    // 初始化图表统计
    initData(chartOpt) {
      const { series } = chartOpt;
      series.forEach(serie => {
        const sum = serie.data.reduce((acc, cur) => acc + cur);
        serie.name === '销售额' ? this.salesTotal = sum * 10000 : this.orderTotal = sum;
      });
    },
    // 缩放图表，统计订单、销量
    getZoomData(data) {
      this.salesTotal = 0;
      this.orderTotal = 0;
      this.chartDate = data[0].data.length;

      data.forEach(d => {
        const sum = d.data.reduce((acc, cur) => acc + cur.data, 0);
        d.name === '销售额' ? this.salesTotal = sum * 1000 : this.orderTotal = sum;
      });
    },
    // 订单提醒跳转
    toNeedPage(path, status) {
      this.$router.push({ path: path, query: { status: status }});
    }
  }
};
</script>

<style lang="scss" scoped>
@import '~@/styles/home.scss';
.home {
  &-container {
    margin: 0;
  }
  &-text {
    font-size: 30px;
    line-height: 46px;
  }
}
</style>
